import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Inventory } from '../entity/inventory.entity';
import { ProductSku } from '../entity/product-sku.entity';
import { InventoryLog, InventoryOperationType } from '../entity/inventory-log.entity';
import {FormatService  } from '../format/format.service'
export class InventoryError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'InventoryError';
  }
}

@Injectable()
export class InventoryService {
  constructor(
    @InjectRepository(Inventory)
    private inventoryRepository: Repository<Inventory>,
    @InjectRepository(ProductSku)
    private skuRepository: Repository<ProductSku>,
    private formatService:FormatService,
    // @InjectRepository(InventoryLog)
    // private inventoryLogRepository: Repository<InventoryLog>
  ) {}

  async adjustStock(skuId: number, quantity: number): Promise<void> {
    await this.skuRepository.manager.transaction(async manager => {

      // console.log('1-2',manager)
      const sku = await manager.findOne(ProductSku, {
        where: { id: skuId },
        lock: { mode: 'pessimistic_write' }
      });

      if (!sku) {
        throw new InventoryError('SKU不存在');
      }

      const inventory = await manager.findOne(Inventory, {
        where: { sku: { id: skuId } },
        lock: { mode: 'pessimistic_write' }
      });

      if (inventory) {
        const newQuantity = inventory.quantity + quantity;
        if (newQuantity < 0) {
          throw new InventoryError('库存不足');
        }
        inventory.quantity = newQuantity;
        await manager.save(inventory);
      } else {
        if (quantity < 0) {
          throw new InventoryError('库存不足');
        }
        const date = this.formatService.dateFormate(new Date(),'YYYY-MM-DD HH:mm:ss.SSSSSS')
        const newInventory = manager.create(Inventory, {
          sku: { id: skuId },
          quantity: quantity,
          created_at:date,
          updated_at:date,
        });
        await manager.save(newInventory);
      }
    });
  }

  async adjustInventory(dto: {
    skuId: number;
    quantity: number;
    operationType: InventoryOperationType;
    notes?: string;
  }): Promise<any> {
    const { skuId, quantity, operationType, notes } = dto;

    await this.skuRepository.manager.transaction(async manager => {
      const sku = await manager.findOne(ProductSku, {
        where: { id: skuId },
        lock: { mode: 'pessimistic_write' }
      });

      if (!sku) {
        throw new InventoryError('SKU不存在');
      }

      const inventory = await manager.findOne(Inventory, {
        where: { sku: { id: skuId } },
        lock: { mode: 'pessimistic_write' }
      });

      // 根据操作类型计算实际数量变化
      const actualQuantity = operationType === InventoryOperationType.SALE ||
                           operationType === InventoryOperationType.LOSS
                           ? -quantity : quantity;

      if (inventory) {
        const newQuantity = inventory.quantity + actualQuantity;
        if (newQuantity < 0) {
          throw new InventoryError('库存不足');
        }
        inventory.quantity = newQuantity;
        await manager.save(inventory);
      } else {
        if (actualQuantity < 0) {
          throw new InventoryError('库存不足');
        }
        const date = this.formatService.dateFormate(new Date(),'YYYY-MM-DD HH:mm:ss.SSSSSS')
        const newInventory = manager.create(Inventory, {
          sku: { id: skuId },
          quantity: actualQuantity,
          updated_at:date,
        });
        await manager.save(newInventory);
      }

      // 创建库存日志
      const date = this.formatService.dateFormate(new Date(),'YYYY-MM-DD HH:mm:ss.SSSSSS')
      const log = manager.create(InventoryLog, {
        sku: { id: skuId },
        quantity: actualQuantity,
        operationType,
        remark: notes || '',
        updatedAt:date,
      });

        const res = await manager.save(log);
        return {
            ...res
        }
    });
  }
}

